package com.infore.exchange.main.config;

import cn.hutool.core.date.DateUtil;
import com.infore.common.model.entity.exchange.TJobInfo;
import com.infore.exchange.main.quartz.CronTaskRegistrar;
import com.infore.exchange.main.quartz.SchedulingRunnable;
import com.infore.exchange.main.service.TJobInfoService;
import com.infore.exchange.main.service.TTaskInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;


/**
 * 项目启动初始化数据
 */
//@Configuration
@Slf4j
public class DataInitializationConfig {


    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;

    @Autowired
    private TJobInfoService jobInfoService;
    @Autowired
    private TTaskInfoService taskInfoService;

    /**
    * @Deacription
    * 由JDK提供了@PostConstruct注解，主要用于在Spring容器启动时执行某些操作或者任务，@PostConstruct注解一般放在BEAN的方法上，
    * 一旦BEAN初始化完成之后，将会调用这个方法。
    * @MethodName init
    * @Author lijianhua
    * @Date 2022/12/17 11:31
    * @最后修改人: lijianhua
    * @最后修改时间：2022/12/17 11:31
    * @Version 4.0
    * @param
    * @return
    **/
    @PostConstruct
    public void init() {
        // 项目启动初始化基本数据
        log.info("数据初始化开始: " + DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        //重置处于(运行中)状态的任务
        taskInfoService.resetAllTaskRunningState();
        //查询需要调度的任务，并加入到调度计划中
        List<TJobInfo> jobInfoQuartzs = jobInfoService.queryHaveTaskJobInfo(null,1,1);
        if (CollectionUtils.isNotEmpty(jobInfoQuartzs)) {
            for (TJobInfo job : jobInfoQuartzs) {
                log.info("需要启动的任务调度\t"+job.getJobName());
                SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getJobId());
                cronTaskRegistrar.addCronTask(task, job.getCronSchedule());
            }
        }
        log.info("数据初始化结束: " + DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
    }
}
